import { Placement, Update } from "../shared/reactFlags";
import { updateFiberNode } from "../shared/utils";
import { IFiber } from "./updateContainer";

export function commitWork(fiber: IFiber) {
  if (!fiber) {
    return;
  }

  // 提交自己
  commitNode(fiber);

  // 递归提交
  commitWork(fiber.child);

  // 递归提交
  commitWork(fiber.sibling);
}

/**
 * 找到父DOM节点
 */
function getParentDOM(fiber: IFiber) {
  let temp = fiber;
  while (temp) {
    if (temp.stateNode) {
      return temp.stateNode;
    }
    temp = temp.return;
  }
  return null;
}

/**
 * 挂在dom节点
 */
function commitNode(wip: IFiber) {
  if (!wip) {
    return;
  }

  // 找到当前fiber的父DOM
  const parentDOM = getParentDOM(wip.return) as HTMLElement;

  const { stateNode, flags } = wip;

  if (!stateNode || !parentDOM) {
    return;
  }

  if (flags & Placement) {
    parentDOM.appendChild(wip.stateNode);
  }

  if (flags & Update) {
    updateFiberNode(wip.stateNode, wip.alternate.props, wip.props);
  }
}
